package freighttmpl

import (
	"context"
	"encoding/json"

	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/api/internal/utils"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/common/utils/pointy"
	"mall/service/setting/rpc/settingclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetFreightTemplateByIdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetFreightTemplateByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetFreightTemplateByIdLogic {
	return &GetFreightTemplateByIdLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetFreightTemplateByIdLogic) GetFreightTemplateById(req *types.IDReq) (resp *types.FreightTemplateInfoResp, err error) {
	if req.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	data, err := l.svcCtx.SettingRpc.BackendGetFreightTemplateById(l.ctx, &settingclient.FreightTemplateIdReq{
		Id:               req.Id,
		WithRestrictions: pointy.GetPointer(uint32(1)),
		WithRules:        pointy.GetPointer(uint32(1)),
	})
	if err != nil {
		return nil, err
	}

	var restrictions []*types.FreightTemplateRestrictionInfo
	if len(data.Restrictions) > 0 {
		for _, v := range data.Restrictions {
			var regions []*types.TreeNode
			if v.Regions != nil {
				if err := json.Unmarshal([]byte(*v.Regions), &regions); err != nil {
					logx.Errorw("GetFreightTemplateById Restrictions.Regions json.Unmarshal err", logx.Field("detail", err.Error()))
				}
			}

			restrictions = append(restrictions, &types.FreightTemplateRestrictionInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id: v.Id,
				},
				TemplateId: v.TemplateId,
				Regions:    regions,
				Mode:       v.Mode,
				Threshold:  v.Threshold,
				Sort:       v.Sort,
				Status:     v.Status,
			})
		}
	}
	var rules []*types.FreightTemplateRuleInfo
	if len(data.Rules) > 0 {
		for _, v := range data.Rules {
			var regions []*types.TreeNode
			if v.Regions != nil {
				if err := json.Unmarshal([]byte(*v.Regions), &regions); err != nil {
					logx.Errorw("GetFreightTemplateById Rules.Regions json.Unmarshal err", logx.Field("detail", err.Error()))
				}
			}

			rules = append(rules, &types.FreightTemplateRuleInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id: v.Id,
				},
				TemplateId:    v.TemplateId,
				Regions:       regions,
				FirstUnit:     v.FirstUnit,
				FirstPrice:    v.FirstPrice,
				ContinueUnit:  v.ContinueUnit,
				ContinuePrice: v.ContinuePrice,
				Sort:          v.Sort,
				Status:        v.Status,
			})
		}
	}

	option := utils.GetOptionByStatus(data.Status)

	return &types.FreightTemplateInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: &types.FreightTemplateInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:         data.Id,
				CreatedAt:  data.CreatedAt,
				UpdatedAt:  data.UpdatedAt,
				DeletedAt:  data.DeletedAt,
				CanAccept:  option.CanAccept,
				CanReject:  option.CanReject,
				CanRemove:  option.CanRemove,
				CanRestore: option.CanRestore,
			},
			Name:         data.Name,
			Remark:       data.Remark,
			FreeShipping: data.FreeShipping,
			ChargeMode:   data.ChargeMode,
			Sort:         data.Sort,
			Status:       data.Status,
			Restrictions: restrictions,
			Rules:        rules,
		},
	}, nil
}
